package admin

import (
	"context"
	"fmt"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/admin/adminLogic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/businessCommonQuery"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
)

func (rpc *admin) AdminOperationLogIndex(ctx context.Context, pb *pbAdmin.AdminOperationLogIndexReq) (*pbAdmin.AdminOperationLogIndexResp, error) {
	where, bindValue, limit, order, e := businessCommonQuery.BuildByBusinessCommonQuery(pb.BusinessCommonQuery)

	if e != nil {
		return nil, businessError.ErrorInfoToRpcError(e)
	}

	adminIds := []interface{}{}
	if pb.OperaterId != 0 {
		if pb.OnlyAuth == 0 {
			adminIds = adminLogic.GetChildrenRoleAdminIds(ctx, pb.OperaterId, true)
		} else {
			adminIds = []interface{}{pb.OperaterId}
		}
		where += " and admin_id in (?)"
		bindValue = append(bindValue, adminIds)
	}

	Db := database.Db.GetDefaultDb(ctx)

	total, dbErr := Db.Find(fmt.Sprintf("select count(*) total from admin_operation_log where 1=1 %s", where), bindValue...)
	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	rows, dbErr := Db.Query(fmt.Sprintf("select * from admin_operation_log where 1=1 %s %s %s", where, order, limit), bindValue...)
	if e != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	resp := &pbAdmin.AdminOperationLogIndexResp{
		Rows:  make([]*pbAdmin.AdminOperationLog, len(rows)),
		Total: total["total"].(int64),
	}

	for i, row := range rows {
		resp.Rows[i] = &pbAdmin.AdminOperationLog{
			Id:         row["id"].(int64),
			AdminId:    row["admin_id"].(int64),
			Username:   row["username"].(string),
			Url:        row["url"].(string),
			Title:      row["title"].(string),
			Content:    row["content"].(string),
			Ip:         row["ip"].(string),
			Useragent:  row["useragent"].(string),
			CreateTime: row["create_time"].(string),
		}
	}

	return resp, nil
}
